<template>
  <div class="OtherCost">
    <!-- 操作栏 -->
    <div class="OtherCost-header">
      <div class="OtherCost-header-search">
        <div class="OtherCost-header-search-item">
          <div class="OtherCost-header-search-item-label">成本名称</div>
          <el-input v-model="searchForm.name" class="OtherCost-header-search-item-input" placeholder="请输入成本名称"
                    clearable/>
        </div>
        <div class="OtherCost-header-search-item">
          <div class="OtherCost-header-search-item-label">日期范围</div>
          <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              unlink-panels
              :shortcuts="dateShortcuts"
              class="OtherCost-header-search-item-input"
          />
        </div>
      </div>
      <div class="OtherCost-header-btn">
        <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" icon="Plus" @click="openAdd">录入</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="OtherCost-table">
      <el-table :data="tableData.list" border stripe class="OtherCost-table-main" v-loading="loading">
        <el-table-column type="index" :index="computeIndex" label="序号" width="60" align="center"/>
        <el-table-column prop="name" label="成本名称" min-width="160" align="center"/>
        <el-table-column prop="cost" label="费用(¥)" width="140" align="center">
          <template #default="{ row }">{{ money(row.cost) }}</template>
        </el-table-column>
        <el-table-column prop="date" label="日期" width="140" align="center"/>
        <el-table-column prop="note" label="备注" min-width="180" align="center">
          <template #default="{ row }">{{ row.note || '-' }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="OtherCost-pagination">
      <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :total="tableData.total"
          :page-sizes="[10,20,50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="OtherCost-pagination-main"
      />
    </div>

    <!-- 独立组件弹窗 -->
    <OtherCostFormDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :initial="editingRecord"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import OtherCostFormDialog from './OtherCostFormDialog.vue'
import { listOtherCosts, addOtherCost, updateOtherCost, deleteOtherCost, getOtherCost } from '../../../api/otherCostApi.js'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  dateRange: []
})

// 日期快捷
const dateShortcuts = [
  {
    text: '最近7天', value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 6);
      return [start, end]
    }
  },
  {
    text: '本月', value: () => {
      const d = new Date();
      const start = new Date(d.getFullYear(), d.getMonth(), 1);
      const end = new Date(d.getFullYear(), d.getMonth() + 1, 0);
      return [start, end]
    }
  }
]
const thisMonthRange = () => {
  const d = new Date();
  return [new Date(d.getFullYear(), d.getMonth(), 1), new Date(d.getFullYear(), d.getMonth() + 1, 0)]
}

// 分页
const pagination = ref({pageNum: 1, pageSize: 10})
const tableData = ref({ list: [], total: 0 })

// 弹窗
const dialogVisible = ref(false)
const dialogTitle = ref('新增其他成本')
const editingRecord = ref(null)

// 工具
const formatDate = (d) => {
  if (!d) return '';
  const dt = new Date(d);
  const y = dt.getFullYear();
  const m = String(dt.getMonth() + 1).padStart(2, '0');
  const dd = String(dt.getDate()).padStart(2, '0');
  return `${y}-${m}-${dd}`
}
const money = (v) => Number(v || 0).toFixed(2)

// 跨页连续序号
const computeIndex = (i) => (pagination.value.pageNum - 1) * pagination.value.pageSize + i + 1

// 构建查询条件
const buildCondition = () => {
  const cond = { name: searchForm.name?.trim() || undefined }
  if (Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2 && searchForm.dateRange[0] && searchForm.dateRange[1]) {
    cond.startDate = formatDate(searchForm.dateRange[0])
    cond.endDate = formatDate(searchForm.dateRange[1])
  }
  return cond
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      condition: buildCondition()
    }
    const res = await listOtherCosts(params)
    tableData.value = { list: res?.list || [], total: res?.total || 0 }
  } catch (e) {
    // 静默或提示
  } finally { loading.value = false }
}

// 搜索
const handleSearch = () => {
  pagination.value.pageNum = 1;
  loadData()
}
// 重置
const handleReset = () => {
  searchForm.name = '';
  searchForm.dateRange = thisMonthRange();
  pagination.value.pageNum = 1;
  loadData()
}

// 分页事件
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.pageNum = 1;
  loadData()
}
const handleCurrentChange = (page) => {
  pagination.value.pageNum = page;
  loadData()
}

// 打开录入
const openAdd = () => {
  dialogTitle.value = '新增其他成本';
  editingRecord.value = null;
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  try {
    const detail = await getOtherCost(row.id)
    dialogTitle.value = '编辑其他成本'
    editingRecord.value = detail || { ...row }
    dialogVisible.value = true
  } catch (e) {
    ElMessage.error('获取成本详情失败')
  }
}
// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除【${row.name}】?`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        await deleteOtherCost(row.id)
        ElMessage.success('删除成功')
        // 若当前页仅一条且删除后页码>1，则回退一页
        if (tableData.value.list.length === 1 && pagination.value.pageNum > 1) {
          pagination.value.pageNum -= 1
        }
        await loadData()
      } catch (e) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 确认新增/编辑
const handleConfirm = async (payload) => {
  try {
    if (payload.id) {
      await updateOtherCost(payload)
      ElMessage.success('更新成功')
    } else {
      await addOtherCost(payload)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    await loadData()
  } catch (e) {
    ElMessage.error(payload.id ? '更新失败' : '新增失败')
  }
}

// 初始化
onMounted(() => {
  searchForm.dateRange = thisMonthRange()
  loadData()
})
</script>

<style scoped lang="scss">
.OtherCost {
  display: flex;
  flex-direction: column;
  height: 100%;

  &-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 16px 0;
    border-bottom: 1px solid #eee;

    &-search {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: center;

      &-item {
        display: flex;
        align-items: center;
        gap: 8px;

        &-label {
          width: 80px;
          font-size: 14px;
          font-weight: 500;
          color: #333;
          white-space: nowrap;
        }

        &-input {
          width: 220px;
        }
      }
    }

    &-btn {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }

  &-table {
    padding: 16px 0;

    &-main {
      width: 100%;
    }
  }

  &-pagination {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    border-top: 1px solid #eee;

    &-main {
      width: 100%;
    }
  }
}
</style>
